﻿using Yxinmt.Interface;
using Yxinmt.Utility;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Yxinmt.Controls
{
    public class WebBrowser : BaseControl, IControl
    {
        private System.Windows.Controls.WebBrowser _WebBrowser { get; set; }

        public Action<System.Windows.Controls.WebBrowser, System.Windows.Navigation.NavigatingCancelEventArgs> Navigating { get; set; }

        public WebBrowser(Dictionary<string, object> property, IComponent component)
        {
            Property = property;
            _Component = component;

            _WebBrowser = new System.Windows.Controls.WebBrowser();
            this.Element = _WebBrowser;

            InitSet();
            this.SetProperty();
            this.SetControlProperty(false, false);
        }

        private void SetProperty()
        {

        }

        public override void EventLoad()
        {
            base.EventLoad();

            SetWebBrowserFeatures(6);
            SetSilent(_WebBrowser, true);

            if (Navigating != null) _WebBrowser.Navigating += _WebBrowser_Navigating;
        }

        void SetWebBrowserFeatures(int ieVersion)
        {
            if (System.ComponentModel.LicenseManager.UsageMode != System.ComponentModel.LicenseUsageMode.Runtime) return;

            var appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            UInt32 ieMode = GeoEmulationModee(ieVersion);

            var featureControlRegKey = @"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\";

            Registry.SetValue(featureControlRegKey + "FEATURE_BROWSER_EMULATION", appName, ieMode, RegistryValueKind.DWord);
            Registry.SetValue(featureControlRegKey + "FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION", appName, 1, RegistryValueKind.DWord);
        }

        public void SetSilent(System.Windows.Controls.WebBrowser browser, bool silent)
        {
            IOleServiceProvider sp = browser.Document as IOleServiceProvider;
            if (sp != null)
            {
                Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
                Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E");

                object webBrowser;
                sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out webBrowser);
                if (webBrowser != null)
                {
                    webBrowser.GetType().InvokeMember("Silent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.PutDispProperty, null, webBrowser, new object[] { silent });
                }
            }
        }

        UInt32 GeoEmulationModee(int browserVersion)
        {
            UInt32 mode = 11000; // Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 Standards mode. 
            switch (browserVersion)
            {
                case 6:
                    {
                        mode = 6000; //edge
                        break;
                    }
                case 7:
                    mode = 7000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. 
                    break;
                case 8:
                    mode = 8000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. 
                    break;
                case 9:
                    mode = 9000; // Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.                    
                    break;
                case 10:
                    mode = 10000; // Internet Explorer 10.
                    break;
                case 11:
                    mode = 11000; // Internet Explorer 11
                    break;
            }
            return mode;
        }

        void _WebBrowser_Navigating(object sender, System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            try
            {
                if (Navigating != null) Navigating(_WebBrowser, e);
            }
            catch (Exception ex)
            {
                LoggerProxy.Exception(Name, "_WebBrowser_Navigating", ex);
            }
        }


        protected override void SetProperty(string name, object value)
        {
            System.Windows.Controls.WebBrowser c = _WebBrowser;
            switch (name)
            {
                case "Name": c.Name = string.Concat("wbr_", (string)value); break;
                case "Height": c.Height = Convert.ToDouble(value); break;
                case "Width": c.Width = Convert.ToDouble(value); break;
                case "Dock": System.Windows.Controls.DockPanel.SetDock(c, this.GetDock((string)value)); break;
                case "ControlAlign": SetControlAlign((string)value); break;
                case "Visible": SetVisible((bool)value); break;
                case "GridRowColumn": SetGridRowColumn((string)value); break;
                case "Url": c.Navigate((string)value); break;
                case "ZIndex": SetZIndex((int)value); break;
            }
        }

        public override void SetValue(object value)
        {
            if (value == null) return;

            _WebBrowser.Navigate(new Uri(value.ToString()));
        }
    }

    [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    public interface IOleServiceProvider
    {
        [PreserveSig]
        int QueryService([In] ref Guid guidService, [In] ref Guid riid, [MarshalAs(UnmanagedType.IDispatch)] out object ppvObject);
    }
}
